package com.bigdata.core.example

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

case class SecondSortKey(val first: Int, val second: Int) extends Ordered[SecondSortKey] {
  /*
  二次排序, 如果first不等, 就按照first的大小排序
  如果first相等, 按照second的大小排序
   */
  override def compare(that: SecondSortKey): Int = {
    if (first != that.first) {
      first - that.first
    } else {
      second - that.second
    }
  }
}


/**
 * 二次排序问题
 */
object SecondSort {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setAppName("secondarySort")
    conf.setMaster("local")
    val sc = new SparkContext(conf)
    sc.setLogLevel("error")

    val lines = sc.textFile("data/secondSort.txt")

    lines.map(data => {
      val splits: Array[String] = data.split(" ")
      (SecondSortKey(splits(0).toInt, splits(1).toInt), data)
    }).sortByKey(false).map(_._2).foreach(println)

  }
}